<template>
  <div class="course-video">
    <el-form label="课程" style="width:500px;margin:0 auto" :inline="true">
      <el-form-item label="课程">
        <el-input disabled="disabled" v-model="courseId">
        </el-input>
      </el-form-item>
      <el-form-item label="课时">
        <el-input disabled="disabled" v-model="courseId">
        </el-input>
      </el-form-item>
    </el-form>
    <el-form style="width:500px;margin:0 auto">
        <el-form-item label="视频上传">
            <input type="file" ref="video-file">
        </el-form-item>
        <el-form-item label="封面上传">
            <input type="file" ref="image-file">
        </el-form-item>
        <el-form-item>
            <el-button type="primary"
            @click="handleUpload">开始上传</el-button>
            <el-button @click="$router.push({
                name: 'course-section',
                params: {
                    courseId
                }
            })">返回</el-button>
        </el-form-item>
        <el-form-item>
            <p v-if="uploadPercent !== 0">上传视频中:{{ uploadPercent }}%</p>
            <p v-if="isUploadSuccess">视频转码中{{ isTranscodeSuccess ? '完成' : '视频转码中...' }}</p>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  aliyunImageUploadAddressAndAuth,
  aliyunVideoUploadAddressAndAuth,
  aliyunTranscode,
  aliyunTranscodePercent
} from '@/services/aliyun-upload'
export default {
  name: 'CourseVideo',
  // 通过props接收父组件传值
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      // 上传图片的地址，用于视频的上传凭证请求
      imageURL: '',
      // 保存上传的实例
      uploader: null,
      // 保存上传视频的ID
      videoId: null,
      // 视频上传进度百分比
      uploadPercent: 0,
      // 保存上传完毕的状态
      isUploadSuccess: false,
      // 转码完毕状态
      isTranscodeSuccess: false
    }
  },
  created () {
    // 初始化上传工具
    this.initUploader()
  },
  methods: {
    handleUpload () {
      // 将数据还原为初始值(可能会重复使用某个组件上传文件的处理,点击上传时将数据重置)
      this.uploadPercent = 0
      this.isUploadSuccess = false
      this.isTranscodeSuccess = false
      // 获取上传的⽂件（视频、图⽚）
      const videoFile = this.$refs['video-file'].files[0]
      const imageFile = this.$refs['image-file'].files[0]
      // 将要上传的文件添加到上传列表中
      const uploader = this.uploader
      uploader.addFile(imageFile)
      uploader.addFile(videoFile)
      // 开始上传
      uploader.startUpload()
    },
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async uploadInfo => {
        //   console.log(uploadInfo)
          // 检测是否是图片或者视频
          // 声明存储图片和视频上传的凭证、地址等信息
          let uploadAddressAndAuth = null
          if (uploadInfo.isImage) {
            // 图片处理
            const { data } = await aliyunImageUploadAddressAndAuth()
            if (data.code === '000000') {
              // console.log(data.data)
              uploadAddressAndAuth = data.data
              // console.log(uploadAddressAndAuth)
              this.imageURL = uploadAddressAndAuth.imageURL
              // 设置凭证与地址
              this.uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAddressAndAuth.uploadAuth,
                uploadAddressAndAuth.uploadAddress,
                uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
              )
            }
          } else {
            // 视频处理
            const { data } = await aliyunVideoUploadAddressAndAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            console.log(data)
            if (data.code === '000000') {
              // console.log(data)
              uploadAddressAndAuth = data.data
              // console.log(uploadAddressAndAuth)
              this.videoId = data.data.videoId
              // console.log(this.videoId)
              // 设置凭证与地址
              this.uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAddressAndAuth.uploadAuth,
                uploadAddressAndAuth.uploadAddress,
                uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
              )
            }
          }
        // 此步设置完毕，上传进度开始执行
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        // 全部文件上传结束
        onUploadEnd: async uploadInfo => {
          this.isUploadSuccess = true
          const lessonId = this.$route.query.lessonId
          // 发送视频请求
          const { data } = await aliyunTranscode({
            // 课时Id
            lessonId,
            // 图片地址
            coverImageUrl: this.imageURL,
            // 视频id
            fileId: this.videoId,
            // 视频文件名称
            fileName: this.$refs['video-file'].files[0].name
          })
          // console.log(data)
          if (data.code === '000000') {
            // 轮循转码进度
            const timer = setInterval(async () => {
              const { data } = await aliyunTranscodePercent(lessonId)
              if (data.code === '000000') {
                // console.log(data)
                this.isTranscodeSuccess = true
                if (data.data === 100) {
                  this.$message.success('视频转码成功')
                  // 清除定时器
                  clearInterval(timer)
                }
              }
            }, 1000)
          }
        }
      })
    }
  }
}

</script>

<style lang="scss" scoped></style>
